package com.flywolf.mooncalendar2013;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnTouchListener {
	final String LOG_TAG = "myLogs";
	Date date;
	boolean otherActions = false;
	MoonData temp;
	int step = 1;
	Date currentDate = new Date();
	MoonDataArray ma = new MoonDataArray();
    Spinner spinnerctrl;
    Button btn;
    Locale myLocale;
	// final String FILENAME = "raw/moondata.csv";

	public Date getCurrentDate() {
		/*
		 * try { currentDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
		 * .parse("2013-05-20 16:00:00"); } catch (ParseException e) { // TODO
		 * Auto-generated catch block e.printStackTrace(); }
		 */
		currentDate = new Date();
		return currentDate;
	}

	public void setCurrentDate(Date currentDate) {
		this.currentDate = currentDate;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ma.readCsv(getResources());
		super.onCreate(savedInstanceState);
		current();

	}

	public void сlickPrev(View view) {
		prev();
	}

	private void prev() {
		otherActions = false;
		date = addDays(date, -1);
		step = 1;
		show(false);
		int id = getResources().getIdentifier(
				getPackageName() + ":string/day" + temp.getMoonDay(), null,
				null);
		String text = getString(id);
		drawToast(text);
		View bottomText = (View) findViewById(R.id.bottom_text);
		bottomText.setVisibility(View.INVISIBLE);
	}

	private void otherActions() {
		Log.d(LOG_TAG, "try other");
		otherActions = !otherActions;
		show(false);
	}

	public void сlickCurrent(View view) {
		current();
	}

	private void current() {
		otherActions = false;
		date = getCurrentDate();
		step = 1;
		show(true);
		int id = getResources().getIdentifier(
				getPackageName() + ":string/day" + temp.getMoonDay(), null,
				null);
		String text = getString(id) + ". "
				+ getString(R.string.simple_description);

		drawToast(text);
		View bottomText = (View) findViewById(R.id.bottom_text);
		bottomText.setVisibility(View.VISIBLE);
	}

	public void сlickNext(View view) {
		next();
	}

	private void next() {
		otherActions = false;
		date = addDays(date, 1);
		step = 1;
		show(false);
		int id = getResources().getIdentifier(
				getPackageName() + ":string/day" + temp.getMoonDay(), null,
				null);
		// Log.d(LOG_TAG, "id="+temp.getMoonDay());
		String text = getString(id);
		drawToast(text);
		View bottomText = (View) findViewById(R.id.bottom_text);
		bottomText.setVisibility(View.INVISIBLE);

	}

	public static Date addDays(Date date, int days) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, days); // minus number would decrement the days
		return cal.getTime();
	}

	/*
	 * public boolean compareDates(Date date, Date nowDate,String time) { String
	 * res = ""; if (date != null) { try { SimpleDateFormat dateformat = new
	 * SimpleDateFormat("yyyy-MM-dd"); StringBuilder nowYYYYMMDD = new
	 * StringBuilder(dateformat.format(date)); res =
	 * nowYYYYMMDD.toString()+" "+time; DateFormat formatter; // Date date;
	 * formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	 * formatter.setLenient(false); date = (Date) formatter.parse(res); } catch
	 * (ParseException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } Log.d(LOG_TAG, "heyaaaaaaaa222!!"+date + " "+
	 * res+" ");
	 * 
	 * } long diff = (date.getTime()+(24 * 60 * 60 * 1000)) - nowDate.getTime();
	 * if (diff > 0 && diff < 24 * 60 * 60 * 1000) { return true; } else {
	 * return false; } }
	 */
	private void show(boolean current) {
		setContentView(R.layout.activity_moon);
		// TextView txt = (TextView) findViewById(R.id.hello);
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		// print(dateFormat.format(new currentDate);
		try {
			// temp = ma.data.get(dateFormat.parse(dateFormat.format(date)));
			TextView txtDate = (TextView) findViewById(R.id.date);
			if (current) {
				temp = ma.getDayByDate(date);
				date = ma.getDate();
				txtDate.setTextColor(Color.parseColor("#669933"));
			}

			else {
				temp = ma.data.get(dateFormat.parse(dateFormat.format(date)));
				txtDate.setTextColor(Color.parseColor("#FF8247"));
			}
			// Log.d(LOG_TAG, dateFormat.format(new currentDate));
			if (temp == null) {
				ImageView day = (ImageView) findViewById(R.id.day);
				day.setImageResource(R.drawable.no_data);
				ImageView sign = (ImageView) findViewById(R.id.sign);
				sign.setImageResource(R.drawable.square);
				ImageView moon = (ImageView) findViewById(R.id.moon);
				moon.setImageResource(R.drawable.square);
			} else {
				boolean isBadDay = ma.badDays.contains(temp.getMoonDay());
				boolean isGoodDay = ma.goodDays.contains(temp.getMoonDay());
				/*
				 * if (temp != null) txt.setText("Moon Day: " +
				 * temp.getMoonDay() + "(" + ma.dateNames.get(temp.getMoonDay())
				 * + "); MoonFase: " + temp.getMoonFase() + "; Sign: " +
				 * temp.getSign() + (isBadDay ? "; bad day" : "") + (isGoodDay ?
				 * "; good day" : "") + "; Grow: " + ma.checkGrow(temp));
				 */
				// else txt.setText("no data");
				dateFormat = new SimpleDateFormat("dd/MM/yyyy E");
				txtDate.setText(dateFormat.format(date) + " "
						+ temp.getMoonRise());
				// Log.d(LOG_TAG,
				// "heyaaaaaaaa!!"+dateFormat.parse(dateFormat.format(date)) +
				// " "+ getCurrentDate()+" ");
				// if (ma.compareDates(getCurrentDate(),temp.getMoonRise())) {
				// txtDate.setTextColor(Color.parseColor("#669933"));
				// } else {full_moon
				// txtDate.setTextColor(Color.parseColor("#FF8247"));
				// }

				ImageView day = (ImageView) findViewById(R.id.day);
				String tag = "";
				int id = getResources().getIdentifier(
						getPackageName() + ":drawable/day" + temp.getMoonDay(),
						null, null);
				if (id != 0)
					day.setImageResource(id);
				ImageView moon = (ImageView) findViewById(R.id.moon);
				int moonN = 1;
				try {
					// int dayN = 0;
					if (temp.getMoonDay() == 102 || temp.getMoonDay() == 3001
							|| temp.getMoonDay() == 30)
						moonN = 2;
					else {
						if (temp.getMoonDay() == 2901
								|| temp.getMoonDay() == 29)
							moonN = 1;
						else
							moonN = (temp.getMoonDay() / 3) + 1;
					}
					/*
					 * switch (dayN) { case 1: moonN=1; break; case (2-3):
					 * moonN=2; break; case (4-6): moonN=3; break; case (7-9):
					 * moonN=4; break; }
					 */
					// Log.d(LOG_TAG, "moonN=" + moonN);
					System.out.println("moonN=" + moonN);
					id = getResources().getIdentifier(
							getPackageName() + ":drawable/moon" + moonN, null,
							null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (id != 0)
					moon.setImageResource(id);

				ImageView sign = (ImageView) findViewById(R.id.sign);
				id = getResources().getIdentifier(
						getPackageName() + ":drawable/" + temp.getSign(), null,
						null);
				if (id != 0)
					sign.setImageResource(id);

				if (!otherActions || step > 9)
					step = 1;
				for (int i = 1; i < 5; i++) {
					id = 0;
					if (step == 1) {
						if (isBadDay) {
							id = R.drawable.bad;
							tag = "bad";
						}
						if (isGoodDay) {
							id = R.drawable.good;
							tag = "good";
						}
						step = 2;
						if (id > 0) {
							fillSquare(id, i, tag);
							continue;
						}
					}
					if (step == 2) {
						id = 0;
						id = ma.checkGrowId(temp);
						step = 3;
						if (id > 0) {
							tag = ma.tag;
							fillSquare(id, i, tag);
							continue;
						}
					}
					if (step == 3) {
						id = 0;

						if (temp.getSign().contentEquals("scorpio")) {
							tag = "manwomen_not_scorpio";
							id = R.drawable.manwomen_question;
						}
						if (ma.manWomenNot.contains(temp.getMoonDay())) {

							tag = "manwomen_not";
							id = R.drawable.manwomen_not;

						}
						if (ma.manWomen.contains(temp.getMoonDay())) {
							tag = "manwomen";
							id = R.drawable.manwomen;
						}
						step = 4;
						if (id > 0) {
							fillSquare(id, i, tag);
							continue;
						}
					}
					if (step == 4) {
						id = 0;
						if (ma.showerNot.contains(temp.getMoonDay())) {
							id = R.drawable.shower_not;
							tag = "shower_not";
						}
						if (ma.shower.contains(temp.getMoonDay())) {
							id = R.drawable.shower;
							tag = "shower";
						}
						step = 5;
						if (id > 0) {
							fillSquare(id, i, tag);
							continue;
						}
					}
					if (step == 5) {
						id = 0;

						if (ma.clear.contains(temp.getMoonDay())) {
							tag = "clear";
							id = R.drawable.clear;
						}
						step = 6;
						if (id > 0) {
							fillSquare(id, i, tag);
							continue;
						}
					}
					if (step == 6) {
						id = 0;
						id = ma.checkFood(temp);
						tag = ma.tag;
						step = 7;
						if (id > 0) {
							fillSquare(id, i, tag);
							continue;
						}
					}
					if (step == 7) {
						id = 0;

						// ImageView signBody = (ImageView)
						// findViewById(R.id.sign);
						id = getResources().getIdentifier(
								getPackageName() + ":drawable/"
										+ temp.getSign() + "_body", null, null);
						step = 8;
						if (id > 0) {
							tag = temp.getSign() + "_body";
							fillSquare(id, i, tag);
							continue;
						}
					}
					if (step == 8) {
						id = 0;

						if (ma.haircut.contains(temp.getMoonDay())) {
							id = R.drawable.haircut;
							tag = "haircut";
						}
						if (ma.haircutNot.contains(temp.getMoonDay())) {
							id = R.drawable.haircut_not;
							tag = "haircut_not";
						}
						step = 9;
						if (id > 0) {
							fillSquare(id, i, tag);
							continue;
						}
					}
					if (step == 9) {
						id = 0;
						switch (temp.getMoonDay()) {
						case 2:
						case 3:
						case 28:
						case 29:
						case 2901:
						case 3001:
							tag = "muladhara";
							id = R.drawable.muladhara;
							break;
						case 4:
						case 5:
						case 26:
						case 27:
							tag = "svadhistana";
							id = R.drawable.svadhistana;
							break;
						case 6:
						case 7:
						case 24:
						case 25:
							tag = "manipura";
							id = R.drawable.manipura;
							break;
						case 8:
						case 9:
						case 22:
						case 23:
							tag = "anahata";
							id = R.drawable.anahata;
							break;
						case 10:
						case 11:
						case 20:
						case 21:
							tag = "vishudha";
							id = R.drawable.vishudha;
							break;
						case 12:
						case 13:
						case 18:
						case 19:
							tag = "adgana";
							id = R.drawable.adgana;
							break;
						case 14:
						case 15:
						case 16:
						case 17:
							tag = "sahasrara";
							id = R.drawable.sahasrara;
							break;
						default:
							id = R.drawable.no_data;
						}
						if (id != R.drawable.no_data) {
							if (temp.getMoonDay() < 16) {
								tag = tag + "_fill";
							} else
								tag = tag + "_realize";
						}
						step = 10;
						if (id > 0) {
							fillSquare(id, i, tag);
							continue;
						}
					}

				}
				day.setOnTouchListener(this);
				moon.setOnTouchListener(this);
				sign.setOnTouchListener(this);

				// TableRow squares = (TableRow) findViewById(R.id.squares);
				// squares.setOnTouchListener(this);
				// /TableRow squares2 = (TableRow) findViewById(R.id.squares2);
				// squares2.setOnTouchListener(this);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void fillSquare(int id, int squareId, String tag) {
		ImageView square = (ImageView) findViewById(R.id.square1);
		switch (squareId) {
		case 1:
			square = (ImageView) findViewById(R.id.square1);
			break;
		case 2:
			square = (ImageView) findViewById(R.id.square2);
			break;
		case 3:
			square = (ImageView) findViewById(R.id.square3);
			break;
		case 4:
			square = (ImageView) findViewById(R.id.square4);
			break;
		}
		if (id != 0)
			square.setImageResource(id);
		square.setTag(tag);
		square.setOnTouchListener(this);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.icon_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.quit:
			quit();
			return true;
		case R.id.next:
			next();
			return true;
		case R.id.previous:
			prev();
			return true;
		case R.id.current:
			current();
			return true;
		case R.id.about:
			about();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void quit() {
		finish();
	}

	private void about() {
		Toast.makeText(this,
				"Moon Calendar 2013.\n Author flywolf1978@gmail.com",
				Toast.LENGTH_LONG).show();
	}

	private void showText(String imgName) {
		String text = "";
		try {
			int id = 0;
			if (imgName.contentEquals("day")) {
				id = getResources().getIdentifier(
						getPackageName() + ":string/day" + temp.getMoonDay(),
						null, null);
				text = getString(R.string.day_symbol) + " " + getString(id);
				drawToast(text);
				return;

			}
			if (imgName.contentEquals("moon")) {
				if (temp.getMoonDay() >= 2 && temp.getMoonDay() <= 16) {
					id = getResources().getIdentifier(
							getPackageName() + ":string/grow_moon", null, null);
				}
				if (temp.getMoonDay() >= 18 && temp.getMoonDay() <= 29) {
					id = getResources().getIdentifier(
							getPackageName() + ":string/wanning_moon", null,
							null);
				}
				if (temp.getMoonDay() == 15) {
					id = getResources().getIdentifier(
							getPackageName() + ":string/full_moon", null, null);
				}
				if (temp.getMoonDay() == 1 || temp.getMoonDay() > 29) {
					id = getResources().getIdentifier(
							getPackageName() + ":string/new_moon", null, null);
				}
			}
			if (imgName.contentEquals("sign")) {
				id = getResources().getIdentifier(
						getPackageName() + ":string/" + temp.getSign(), null,
						null);
			}
			text = getString(id);
		} catch (Exception ex) {
			text = getString(R.string.no_description);
		}
		drawToast(text);
	}

	private void showTextS(String key, int id) {
		String text = "";
		try {
			id = getResources().getIdentifier(
					getPackageName() + ":string/" + key, null, null);
			text = getString(id);
		} catch (Exception ex) {
			text = getString(R.string.no_description);
		}
		drawToast(text);
	}

	private void drawToast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();

	}

	static final int MIN_DISTANCE = 25;
	private float downX, downY, upX, upY;

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		Log.d(LOG_TAG, "check sweep");
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: {
			downX = event.getX();
			downY = event.getY();
			return true;
		}
		case MotionEvent.ACTION_UP: {
			upX = event.getX();
			upY = event.getY();

			float deltaX = downX - upX;
			float deltaY = downY - upY;

			// swipe horizontal?
			if (Math.abs(deltaX) > MIN_DISTANCE) {
				// left or right
				if (deltaX < 0) {
					if (v.getId() == R.id.square1 || v.getId() == R.id.square2
							|| v.getId() == R.id.square3
							|| v.getId() == R.id.square4)
						otherActions();
					else
						prev();
					return true;
				}
				if (deltaX > 0) {
					if (v.getId() == R.id.square1 || v.getId() == R.id.square2
							|| v.getId() == R.id.square3
							|| v.getId() == R.id.square4)
						otherActions();
					else
						next();
					return true;
				}
			} else {
				if (v.getId() == R.id.square1 || v.getId() == R.id.square2
						|| v.getId() == R.id.square3
						|| v.getId() == R.id.square4)
					showTextS((String) v.getTag(), v.getId());
				else
					showText((String) v.getTag());
			}

			/*
			 * if (Math.abs(deltaY) > MIN_DISTANCE) { // left or right if
			 * (deltaY < 0) { if (v.getId() == R.id.square1 || v.getId() ==
			 * R.id.square2 || v.getId() == R.id.square3 || v.getId() ==
			 * R.id.square4) otherActions(); else prev(); return true; } if
			 * (deltaY > 0) { if (v.getId() == R.id.square1 || v.getId() ==
			 * R.id.square2 || v.getId() == R.id.square3 || v.getId() ==
			 * R.id.square4) otherActions(); else next(); return true; } } else
			 * { if (v.getId() == R.id.square1 || v.getId() == R.id.square2 ||
			 * v.getId() == R.id.square3 || v.getId() == R.id.square4)
			 * showTextS((String) v.getTag(), v.getId()); else showText((String)
			 * v.getTag()); }
			 */

			return true;
		}
		}
		return false;
	}

}
